/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package estg.dae.projecto.broker.data;

import estg.dae.projecto.broker.model.Bank;
import java.util.Collection;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

/**
 *
 * @author mario
 */
@Stateless
public class BankDao implements BankDaoLocal {
    @PersistenceContext(unitName = "Broker-ejb-PersistenceUnit")
    private EntityManager entityManager;

    public Bank get(String code) {
        return (Bank ) entityManager.createQuery("SELECT b FROM Bank b WHERE b.code = ?1")
                .setParameter(1, code)
                .getSingleResult();
    }
    public Bank get(long id) {
        return entityManager.find(Bank .class, id);
    }
    public void save(Bank  bank){
        entityManager.persist(bank);
        entityManager.flush();
        entityManager.clear();
    }
    public void update(Bank  bank){
        entityManager.merge(bank);
        entityManager.flush();
        entityManager.clear();
    }
    public Collection<Bank> getAll(){
        return entityManager.createQuery("SELECT b FROM Bank b")
                .getResultList();
    }

    public boolean exists(String code) {
         Long result = (Long) entityManager.createQuery("SELECT count(b) FROM Bank b WHERE b.code = ?1")
                .setParameter(1, code)
                .getSingleResult();

         return result.longValue() == 1;
    }
}
